import os
import sys
import time
from os.path import exists

import requests
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QMdiSubWindow, QWidget
import _thread

import KNN
import getdata
import successui


class Ui_MainWindow(object):
    n = 0  #####第n张图片
    num = 0  #####一共 num*30 张图片
    index = 10



    def setupUi(self, MainWindow):
        # self.second=getdata.Ui_MainWindow()
        # self.splitter.addWidget(self.first)
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(653, 366)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(80, 50, 161, 41))
        self.textEdit.setObjectName("textEdit")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(480, 310, 93, 28))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(150 + 93, 270, 93, 28))
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_4.setGeometry(QtCore.QRect(257 + 93, 270, 93, 28))
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_5.setGeometry(QtCore.QRect(143, 270, 93, 28))
        self.pushButton_5.setObjectName("pushButton_5")
        self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
        self.scrollArea.setGeometry(QtCore.QRect(250, 50, 361, 141))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 359, 139))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.textEdit_2 = QtWidgets.QTextEdit(self.scrollAreaWidgetContents)
        self.textEdit_2.setGeometry(QtCore.QRect(0, 0, 361, 141))
        self.textEdit_2.setObjectName("textEdit_2")
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(10, 60, 72, 15))
        self.label.setObjectName("label")

        self.textEdit_3 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_3.setGeometry(QtCore.QRect(70, 120, 81, 31))
        self.textEdit_3.setObjectName("textEdit_3")
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(40, 270, 87, 22))
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.comboBox.activated.connect(self.on_combobox_Activate)

        self.textEdit_2.append('时间原因有几个BUG不是很好改所以将就这用把')
        self.retranslateUi(MainWindow)
        self.pushButton_2.clicked.connect(MainWindow.close)
        self.pushButton_3.clicked.connect(self.textEdit_3.clear)
        self.pushButton_3.clicked.connect(self.textEdit_2.clear)
        self.pushButton_3.clicked.connect(self.textEdit.clear)
        self.pushButton_4.clicked.connect(self.img_text)
        self.pushButton_5.clicked.connect(self.chose)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    # def change(self, name):
    #     if name == "pushButton":  # 这句的意思是把现在 splitter 的界面设置为None,也就是去掉
    #         self.splitter.widget(1).setParent(None)  # 把另一个self.first这个界面插入上一句去掉的那个界面的位置
    #         self.splitter.insertWidget(1, self.first)
    #     if name == "pushButton_2":
    #         self.splitter.widget(1).setParent(None)
    #         self.splitter.insertWidget(1, self.second)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.textEdit.setHtml(_translate("MainWindow",
                                         "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                                         "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                                         "p, li { white-space: pre-wrap; }\n"
                                         "</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
                                         "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">例:胡歌,张国荣,许嵩</p></body></html>"))
        self.pushButton_2.setText(_translate("MainWindow", "退出"))
        self.pushButton_3.setText(_translate("MainWindow", "清空"))
        self.pushButton_4.setText(_translate("MainWindow", "爬取图片"))
        self.pushButton_5.setText(_translate("MainWindow", "生成数据"))
        self.label.setText(_translate("MainWindow", "输入名字"))
        self.textEdit_3.setHtml(_translate("MainWindow",
                                           "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                                           "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                                           "p, li { white-space: pre-wrap; }\n"
                                           "</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
                                           "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">1</p></body></html>"))
        self.comboBox.setItemText(0, _translate("MainWindow", "选择算法"))
        self.comboBox.setItemText(1, _translate("MainWindow", "生成数据"))
        self.comboBox.setItemText(2, _translate("MainWindow", "K-means"))
        self.comboBox.setItemText(3, _translate("MainWindow", "KNN"))
        self.comboBox.setItemText(4, _translate("MainWindow", "DB"))
        if exists("./data/train_data") and exists("./data/lablae"):
            self.textEdit_2.append('已经在 data 文件下生成数据，可以选择再次生成数据')
        else:
            self.textEdit_2.append('data文件下没有数据文件请先 生成数据文件')

    def on_combobox_Activate(self):  ###################处理下拉框事件

        if self.comboBox.currentIndex()==3:
            self.MainWindow = QWidget()
            self.ui = KNN.Ui_MainWindow()
            self.ui.setupUi(MainWindow)
        if self.comboBox.currentIndex()==0:
            self.textEdit_2.append("请选择算法。")
        else:
            self.textEdit_2.append("时间问题目前没有实现此功能！")

    def data(self):
        self.index = int(self.comboBox.currentIndex())

    def chose(self):
        # if self.index == 1:
        #     _thread.start_new_thread(getdata.run(),())
        # else:
        #     self.textEdit_2.append("还未实现此功能")
        # aa = getdata.Ui_MainWindow()
        # aa.show()
        # sys.exit(aa.exec_())

        # self.ui = getdata.data_ui()
        # self.ui.setupUi()
        # self.ui.show()

        # self.app = QApplication(sys.argv)
        self.MainWindow = QWidget()
        self.ui = getdata.data_ui()
        self.ui.setupUi(MainWindow)
        # self.MainWindow.show()

        # sys.exit(app.exec_())
        # self.aa = getdata.data_ui()
        # self.aa.show()

        ########            报错之前看看是否联网了

    def img_text(self):
        global name
        name = self.textEdit.toPlainText()
        # name_list = text_2.split(',')
        #     self.str = '爬取{0}_第{1}张图片'.format(name,self.n)
        _thread.start_new_thread(self.get_image, (self.n, name,))


    def get_image(self, n, name):
        print("我是 get_image")
        self.name = name
        self.url = 'https://image.baidu.com/search/acjson?'
        self.headers = {

            'Cookie': 'BDqhfp=%E7%8B%97%26%260-10-1undefined%26%260%26%261; BIDUPSID=E5B9CDED7071EEEE2A89CAB9C2E11AD7; PSTM=1623558395; BAIDUID=FAC888944227661413FCC9BC4AB0F78F:FG=1; __yjs_duid=1_18022e2bb8011c006a066cea2beedb2f1626079007527; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; BAIDUID_BFESS=FAC888944227661413FCC9BC4AB0F78F:FG=1; BDRCVFR[FIXrT5n2Tgt]=mk3SLVN4HKm; H_PS_PSSID=31660_26350; BA_HECTOR=212481agakag0505291ggch9l0q; BDRCVFR[X_XKQks0S63]=mk3SLVN4HKm; userFrom=www.baidu.com; firstShowTip=1; indexPageSugList=%5B%22%E7%8B%97%22%5D; cleanHistoryStatus=0; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm; ab_sr=1.0.1_YWM1NDBjODBkMzFhYzNiMTc1ZmIzYjY1YjUyOTQ5ZjBkZjg0MDQ0MWQyMDY2YmIzMzVlNTZmMDk5Zjg5MzAxYjBlNjVlNDU3ODZkNjQwZWIxMDNjNjgzYjAyNWZkYmEyZTQ3NTNlYTZlOWE4MGZhMWY0MmUwNzBjYmRiNzQ4NzNiNWM3YmMyZmM0OGNjMzYzNmU2ZjEzYWM0MTBkODhkYw==; BDRCVFR[-pGxjrCMryR]=mk3SLVN4HKm',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'
        }
        self.params = {
            'tn': 'resultjson_com',
            'logid': '10121964150891701915',
            'ipn': 'rj',
            'ct': '201326592',
            'is': '',
            'fp': 'result',
            'queryWord': '狗',
            'cl': '2',
            'lm': '-1',
            'ie': 'utf-8',
            'oe': 'utf-8',
            'adpicid': '',
            'st': '-1',
            'z': '',
            'ic': '0',
            'hd': '',
            'latest': '',
            'copyright': '',
            'word': '{}'.format(name),
            's': '',
            'se': '',
            'tab': '',
            'width': '',
            'height': '',
            'face': '0',
            'istype': '2',
            'qc': '',
            'nc': '1',
            'fr': '',
            'expermode': '',
            'nojc': '',
            'pn': '',
            'rn': '30',
            'gsm': '',
            'time': ''
        }
        self.img_list = []

        for i in range(0, int(self.textEdit_3.toPlainText())):
            self.params['time'] = int(time.time() * 1000)
            self.params['pn'] = i * 30
            response = requests.get(url=self.url, headers=self.headers, params=self.params)
            try:

                for j in range(0, len(response.json()['data']) - 1):
                    self.img_list.append(response.json()['data'][j]['thumbURL'])
            except Exception:
                self.textEdit_2.setText("没有这么多图片")
        ########            报错了看看是否联网了
        for j in self.img_list:
            strs = '爬取{0}_第{1}张图片'.format(name, n)
            self.textEdit_2.append(strs)
            image = requests.get(url=j)
            if not os.path.exists('./img/{}'.format(name)):
                os.mkdir('./img/{}'.format(name))
            with open('./img/{2}/{0}.{1}.jpg'.format(name, n, name), 'wb') as f:
                f.write(image.content)
            n += 1
        successui.run('爬取成功')
        # getdata.run()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
